﻿using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using Avalonia.Controls;
using CommunityToolkit.Mvvm.Input;
using EmotionChat.Services;
using Mvvm.Services;
using ReactiveUI;

namespace Mvvm.ViewModels
{
    /// <summary>
    ///  This is our ViewModel for the first page
    /// </summary>
    public class FirstPageViewModel : PageViewModelBase
    {
        private IChatDataStorage _chatDataStorage;
        private readonly ChatDataProcessService _chatDataProcessService;
        private IChatDataProcessedStorage _chatDataProcessedStorage;
        private bool _isLoading; // 控制加载弹窗显示
        public FirstPageViewModel()
        {
            _chatDataStorage = new ChatDataStorage();
            _chatDataProcessService = new ChatDataProcessService();
            _chatDataProcessedStorage = new ChatDataProcessedStorage();
            SaveChatDataCommand = new RelayCommand<string>(SaveChatData);
            AnalyzeChatDataCommand = new AsyncRelayCommand(Analyze);
            ClearCommand = new AsyncRelayCommand(DeleteAsync);
        }
        private bool _isPopupOpen;
        private string _message;
        private string _processedData = string.Empty;
        public bool IsLoading
        {
            get => _isLoading;
            set => this.RaiseAndSetIfChanged(ref _isLoading, value);
        }
        public bool IsPopupOpen
        {
            get => _isPopupOpen;
            set => this.RaiseAndSetIfChanged(ref _isPopupOpen, value);
        }

        public string Message
        {
            get => _message;
            set => this.RaiseAndSetIfChanged(ref _message, value);
        }
        public string ProcessedData
        {
            get => _processedData;
            set => this.RaiseAndSetIfChanged(ref _processedData, value);
        }
        private async void SaveChatData(string? input)
        {
            // 显示加载弹窗
            IsLoading = true;
            //await _chatDataStorage.InitializeAsync();
            string chatData = input;;
            _chatDataStorage = new ChatDataStorage();
            await _chatDataStorage.InitializeAsync();
            // 将聊天数据插入数据
            var chatDataList = _chatDataProcessService.ParseChatLog(chatData);
            // 提取关键词，并加到chatDataList中的每一个chatData中
            _chatDataProcessService.ExtractKeywords(chatDataList);
     
            // 这里需要填充情绪的数据，请直接处理chatDataList增加情绪的数据，可以参考上述增加关键词的逻辑
            await _chatDataProcessService.AddEmotionalAnalysisToChatData(chatDataList);
        
            // 读取数据库中的全部聊天数据，找到最大的identifier
            var chatDatas = await _chatDataStorage.ListAsync();
            int identifier = chatDatas.Count > 0 ? chatDatas.Max(cd => cd.Identifier) : 0;
        
            // 将chatDataList插入数据库
            await _chatDataStorage.InsertAllAsync(chatDataList,identifier+1);
            // 设置弹窗消息并打开弹窗
            Message = "聊天数据已保存！";
            IsPopupOpen = true;
            // 三秒后关闭弹窗
            await Task.Delay(3000);
            IsPopupOpen = false;
            // 关闭加载弹窗
            IsLoading = false;
            await Analyze();
        }

        // This is our first page, so we can navigate to the next page in any case
        public override bool CanNavigateNext 
        { 
            get => true;
            protected set => throw new NotSupportedException(); 
        }

        // You cannot go back from this page
        public override bool CanNavigatePrevious
        {
            get => false;
            protected set => throw new NotSupportedException();
        }
        public ICommand SaveChatDataCommand { get; }
        public ICommand AnalyzeChatDataCommand { get; set; }
        public ICommand ClearCommand { get; set; }

        private async Task Analyze() {
            _chatDataStorage = new ChatDataStorage();
            var chatDatas = await _chatDataStorage.ListAsync();
            try
            {
                var chatProcessedData  = _chatDataProcessService.ProcessChatData(chatDatas);
                _chatDataProcessedStorage = new ChatDataProcessedStorage();
                // 遍历数据库，找到最大的identifier,否则设为0
                var maxIdentifier = chatDatas.Max(cd => cd.Identifier);
                if (chatDatas.Count == 0)
                {
                    maxIdentifier = 0;
                }
                await _chatDataProcessedStorage.InsertAsync(chatProcessedData,maxIdentifier);
                ProcessedData = _chatDataProcessService.PrintProcessedservice(chatProcessedData);
                // 打印_chatDataProcessedStorage的所有数据
                var chatProcessedDatas = await _chatDataProcessedStorage.ListAsync();
                foreach (var chatProcessedData1 in chatProcessedDatas) {
                    Console.WriteLine(chatProcessedData1.Identifier);
                }
                Message = "已完成分析！";
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Message = "输入数据格式异常！";
                // 设置弹窗消息并打开弹窗
                IsPopupOpen = true;
                // 三秒后关闭弹窗
                await Task.Delay(3000);
                IsPopupOpen = false;
                return;
            }
            
            // 设置弹窗消息并打开弹
            IsPopupOpen = true;
            // 三秒后关闭弹窗
            await Task.Delay(3000);
            IsPopupOpen = false;
        }
        private async Task DeleteAsync() {
            try {
                _chatDataStorage = new ChatDataStorage();
                await _chatDataStorage.DeleteAsync();
                _chatDataProcessedStorage = new ChatDataProcessedStorage();
                await _chatDataProcessedStorage.DeleteAsync();

            } catch (Exception ex) {
                // 记录异常日志
                Console.WriteLine($"DeleteAsync failed: {ex.Message}");
            }
        }
    }
}
